<template>
  <div>
    <div class="flex-between mb-16">
      <h2>用户管理</h2>
      <a-button type="primary" @click="handleAdd">
        <PlusOutlined />
        新建用户
      </a-button>
    </div>

    <a-table
      :columns="columns"
      :data-source="dataSource"
      :pagination="pagination"
      :loading="loading"
      @change="handleTableChange"
      row-key="id"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'status'">
          <a-tag :color="record.status === 1 ? 'green' : 'red'">
            {{ record.status === 1 ? '启用' : '禁用' }}
          </a-tag>
        </template>
        <template v-else-if="column.key === 'action'">
          <a-space>
            <a-button type="link" size="small" @click="handleEdit(record)">编辑</a-button>
            <a-popconfirm
              title="确定删除这个用户吗？"
              ok-text="确定"
              cancel-text="取消"
              @confirm="handleDelete(record.id)"
            >
              <a-button type="link" danger size="small">删除</a-button>
            </a-popconfirm>
          </a-space>
        </template>
      </template>
    </a-table>

    <!-- 新建/编辑弹窗 -->
    <a-modal
      v-model:open="modalVisible"
      :title="modalTitle"
      @ok="handleSubmit"
      @cancel="handleCancel"
      width="600px"
    >
      <a-form :model="formState" :label-col="{ span: 5 }" :wrapper-col="{ span: 19 }">
        <a-form-item label="用户名" required>
          <a-input v-model:value="formState.username" placeholder="请输入用户名" :disabled="!!editId" />
        </a-form-item>
        <a-form-item label="邮箱" required>
          <a-input v-model:value="formState.email" placeholder="请输入邮箱" />
        </a-form-item>
        <a-form-item v-if="!editId" label="密码" required>
          <a-input-password v-model:value="formState.password" placeholder="请输入密码" />
        </a-form-item>
        <a-form-item label="昵称">
          <a-input v-model:value="formState.nickname" placeholder="请输入昵称" />
        </a-form-item>
        <a-form-item label="状态">
          <a-radio-group v-model:value="formState.status">
            <a-radio :value="1">启用</a-radio>
            <a-radio :value="0">禁用</a-radio>
          </a-radio-group>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import { PlusOutlined } from '@ant-design/icons-vue'
import { getUsers, createUser, updateUser, deleteUser } from '@/api/user'
import type { UserInfo } from '@/types'

const columns = [
  { title: 'ID', dataIndex: 'id', key: 'id', width: 80 },
  { title: '用户名', dataIndex: 'username', key: 'username' },
  { title: '邮箱', dataIndex: 'email', key: 'email' },
  { title: '昵称', dataIndex: 'nickname', key: 'nickname' },
  { title: '状态', dataIndex: 'status', key: 'status', width: 100 },
  { title: '最后登录', dataIndex: 'last_login_time', key: 'last_login_time', width: 180 },
  { title: '创建时间', dataIndex: 'created_at', key: 'created_at', width: 180 },
  { title: '操作', key: 'action', width: 150 }
]

const dataSource = ref<UserInfo[]>([])
const loading = ref(false)
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0
})

const modalVisible = ref(false)
const modalTitle = ref('新建用户')
const editId = ref<number>()
const formState = reactive({
  username: '',
  email: '',
  password: '',
  nickname: '',
  status: 1
})

const fetchUsers = async () => {
  loading.value = true
  try {
    const res = await getUsers({
      page: pagination.current,
      page_size: pagination.pageSize
    })
    dataSource.value = res.data.items
    pagination.total = res.data.total
  } catch (error) {
    console.error('获取用户列表失败', error)
  } finally {
    loading.value = false
  }
}

const handleTableChange = (pag: any) => {
  pagination.current = pag.current
  pagination.pageSize = pag.pageSize
  fetchUsers()
}

const handleAdd = () => {
  modalTitle.value = '新建用户'
  editId.value = undefined
  Object.assign(formState, {
    username: '',
    email: '',
    password: '',
    nickname: '',
    status: 1
  })
  modalVisible.value = true
}

const handleEdit = (record: UserInfo) => {
  modalTitle.value = '编辑用户'
  editId.value = record.id
  Object.assign(formState, {
    username: record.username,
    email: record.email,
    nickname: record.nickname,
    status: record.status
  })
  modalVisible.value = true
}

const handleSubmit = async () => {
  try {
    if (editId.value) {
      const { password, ...updateData } = formState
      await updateUser(editId.value, updateData)
      message.success('更新成功')
    } else {
      await createUser(formState)
      message.success('创建成功')
    }
    modalVisible.value = false
    fetchUsers()
  } catch (error) {
    console.error('提交失败', error)
  }
}

const handleCancel = () => {
  modalVisible.value = false
}

const handleDelete = async (id: number) => {
  try {
    await deleteUser(id)
    message.success('删除成功')
    fetchUsers()
  } catch (error) {
    console.error('删除失败', error)
  }
}

onMounted(() => {
  fetchUsers()
})
</script>

